package com.cl.blog.service.impl;

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 付
 * @Date 2024-04-10 10:09
 * @Version 1.0
 * @description 敏感词业务类，读取敏感词文件的数据
 * @since 1.0
 */
@Service
public class FileReadingService {

	private final ResourceLoader resourceLoader;

	public FileReadingService(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	public Map<String, String[]> readKeyValuePairs() {
		Map<String, String[]> keyValuePairs = new HashMap<>();
		try {
			// 加载资源
			Resource resource = resourceLoader.getResource("classpath:dict_tag_test.txt");
			// 读取文件内容
			try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
				String line;
				while ((line = reader.readLine()) != null) {
					// 分割每一行的key和value
					String[] parts = line.split("\\s+", 2); // 使用空格分割，并限制分割次数为2次，以防止值中的空格干扰
					if (parts.length == 2) {
						// 分割values
						String[] values = parts[1].split(",");
						// 将key和values存入map
						keyValuePairs.put(parts[0], values);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("Error reading file", e);
		}
		return keyValuePairs;
	}
}
